#!/bin/bash
#安装mysql
 yum -y install mysql-server mysql mysql-devel
#重启停止mysql服务
systemctl restart mysqld.service
systemctl stop  mysqld.service

# 删除MySQL数据目录中的所有文件
sudo rm -rf /var/lib/mysql/*

sudo truncate -s 0 /var/log/mysql/mysqld.log

# 使用初始化选项重新初始化MySQL
sudo mysqld --initialize

# 查找并提取临时密码
temp_password=$(sudo grep 'temporary password' /var/log/mysql/mysqld.log | awk '{print $NF}')
# 打印临时密码
echo "Temporary password: $temp_password"
#mysql目录下修改所有者和组、重启服务
sudo chown -R mysql:mysql /var/lib/mysql
systemctl restart mysqld.service 
#修改密码
mysql -u root -p"$temp_password"  --connect-expired-password   -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$password';"

if [ $? -eq 0 ]; then
    echo "MySQL root password updated."
else
    echo "Error: Failed to update MySQL root password."
fi

# 创建数据库
mysql -u root -p$password -e "CREATE DATABASE $db;"

# 创建用户并授予权限
mysql -u root -p$password -e "CREATE USER '$user'@'%' IDENTIFIED BY '$password';"
mysql -u root -p$password -e "GRANT ALL PRIVILEGES ON $db.* TO '$user'@'%';"

# 刷新权限
mysql -u root -p$password -e "FLUSH PRIVILEGES;"


echo "MySQL configuration and user setup completed successfully."


